package com.easy.interceptor;

import com.alibaba.fastjson.JSON;
import com.easy.util.LayData;
import com.easy.util.SYS;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShoppingLoginINterceptor implements HandlerInterceptor {
    //在Handler处理之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查请求是否有登录状态
        HttpSession session =request.getSession();
        Object obj=session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        //判断是否存在登录数据
        if(obj!=null){
            return true;
        }else {
            //分支判断   请求方式    访问页面(shopping/页面名)  重定向
            //                     ajax                    json
            //重定向
            String requestwith=request.getHeader("X-Requested-With");
            if("XMLHttpRequest".equals(requestwith)){
                //ajax
                LayData result=  LayData.success(401,"您还没有登录,请登录");
                String json= JSON.toJSONString(result);
                response.setHeader("Content-Type","application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);
            }else {
                //跳转页面请求
                String path = request.getContextPath();
                String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
                response.sendRedirect(basePath + "shopping/login");
            }
            return false;
        }
    }
//在Handler处理之后立即执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
//一个请求结束spring框架访问后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
